import $ from "jquery";
import NP from "number-precision";
import router from "../router";
import store from "../store";
import { createDiscreteApi } from "naive-ui";
const $Message = createDiscreteApi(["message"]).message;

// 静态资源加载
export const getAssets = (file) => {
  const path = "tp.rth5.com";
  console.log("window.location.host.includes(path) => ", window.location.host.includes(path));
  if (window.location.host.includes(path)) {
    return `https://${path}/img/${file}`;
  } else {
    return new URL(`../assets/${file}`, import.meta.url).href;
  }
};

export const userImgError = (e) => {
  e.srcElement.src = new URL("../assets/img/icon/user_empty.jpg", import.meta.url).href;
};

//export导出文件
export const exportBlobFile = (res) => {
  // console.log(res);
  var blob = new Blob([res.data], {
    type: "application/vnd.ms-excel;charset=utf-8"
  });
  var downloadElement = document.createElement("a");
  var href = window.URL.createObjectURL(blob); // 创建下载的链接
  downloadElement.href = href;
  downloadElement.download = decodeURI(res.headers["content-disposition"].split("filename=")[1].replace(/\/|"/g, "")) || ""; // 下载后文件名
  document.body.appendChild(downloadElement);
  downloadElement.click(); // 点击下载
  document.body.removeChild(downloadElement); // 下载完成移除元素
  window.URL.revokeObjectURL(href); // 释放掉blob对象
};

export const isEmpty = (a) => {
  /* 检验空格 */
  if (typeof a == "string" && a.replace(/(^\s*)|(\s*$)/g, "") === "") return true;
  /* 检验空字符串 */
  if (a === "") return true;
  /* 检验字符串类型的null */
  if (a === "null") return true;
  /* 检验字符串类型的 undefined	*/
  if (a === "undefined") return true;
  /* 检验 undefined 和 null */
  if (!a && a !== 0 && a !== "") return true;
  /* 检验空数组	*/
  if (Object.prototype.isPrototypeOf.call(Array.prototype, a) && a.length === 0) return true;
  /* 检验空对象  */
  if (Object.prototype.isPrototypeOf.call(Object.prototype, a) && Object.keys(a).length === 0) return true;
  return false;
};

// 清空LocalStorage
export const localStorageClear = () => {
  localStorage.clear();
};

// 保存LocalStorage
export const localStorageSet = (key, value = {}, type = null) => {
  if (type === "object") {
    localStorage.setItem(key, JSON.stringify(value));
    return localStorage.getItem(key);
  } else {
    localStorage.setItem(key, value);
    return localStorage.getItem(key);
  }
};

// 获取LocalStorage
export const localStorageGet = (key, type = null) => {
  if (type === "object") {
    return JSON.parse(localStorage.getItem(key));
  }
  return localStorage.getItem(key);
};

// 删除指定LocalStorage
export const localStorageRemoveItem = (key) => {
  localStorage.removeItem(key);
};

// sessionStorage页面存在期间有效
// 清空sessionStorage
export const sessionStorageClear = () => {
  sessionStorage.clear();
};

// 保存sessionStorage
export const setSessionStorage = (key, value = {}, type = null) => {
  if (type === "object") {
    sessionStorage.setItem(key, JSON.stringify(value));
    return sessionStorage.getItem(key);
  }
  sessionStorage.setItem(key, value);
  return sessionStorage.getItem(key);
};

// 获取sessionStorage
export const getSessionStorage = (key, type = null) => {
  if (type === "object") {
    return JSON.parse(sessionStorage.getItem(key));
  }
};

// 文本复制
export const copyText = (text) => {
  let textarea = document.createElement("textarea"); // 创建input对象
  let currentFocus = document.activeElement; // 当前获得焦点的元素
  let toolBoxwrap = document.getElementById("app");
  toolBoxwrap.appendChild(textarea); // 添加元素
  textarea.value = text;
  textarea.focus();
  if (textarea.setSelectionRange) {
    textarea.setSelectionRange(0, textarea.value.length); // 获取光标起始位置到结束位置
  } else {
    textarea.select();
  }
  let flag;
  try {
    flag = document.execCommand("copy"); // 执行复制
  } catch (eo) {
    flag = false;
  }
  toolBoxwrap.removeChild(textarea); // 删除元素
  currentFocus.focus();
  $Message.success("Copy success.");
  return flag;
};

// 控制input前后不能输入空格
export const noSideSpace = (value) => !value.startsWith(" ") && !value.endsWith(" ");

// 控制input不能输入空格
export const noSpace = (value) => value.replace(/\s/g, "");

// 获取当前环境
export const getEnv = (type = 1) => {
  if (location.host.includes("studio-test")) {
    return type === 1 ? "test" : "-test";
  } else if (
    location.host.includes("studio-dev") ||
    location.host.includes("127.") ||
    location.host.includes("192.") ||
    location.host.includes("local")
  ) {
    return type === 1 ? "dev" : "-dev";
  } else if (location.host.includes("studio-pre")) {
    return type === 1 ? "pre" : "-pre";
  } else if (location.host.includes("studio")) {
    return type === 1 ? "prod" : "";
  }
};

// 初始化 googleSigin
export const googleClientInit = (
  googleSiginConfig = {
    client_id: "319810593364-a7gitcom2a3njl0ptf8lnbqr6oitb1dq.apps.googleusercontent.com",
    scope: "profile email openid",
    access_type: "offline"
  },
  callback = () => {}
) => {
  return window.google?.accounts.oauth2.initTokenClient({
    ...googleSiginConfig,
    callback: (res) => {
      callback(res);
    }
  });
};

// 初始化 faceBook SDK
export const fbAsyncInit = (appId = "376588044779828", callBack = () => {}) => {
  // console.log("fbAsyncInit----", window.FB);
  if (!window.FB) {
    $.getScript(`https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v16.0&appId=${appId}&autoLogAppEvents=1`, () => {
      window.fbAsyncInit = () => {
        // console.log("fbAsyncInit:", window.FB);
        window.FB.init({
          appId: appId, //facebook申请的的appid
          cookie: true, // enable cookies to allow the server to access
          xfbml: true, // parse social plugins on this page
          version: "v16.0" // use graph api version 2.8
        });
        callBack();
      };
    });
  } else {
    callBack();
  }
};

// 退出登录
export const logOut = () => {
  // console.log("logOut-store", store);
  // console.log("logOut-router", router);
  store.commit("UPDATE_USERINFO", {});
  store.commit("UPDATE_AUTHORIZATION", "");
  router.push("/login");
};

export const formatInit = (time) => {
  let hour = Math.floor(time / 3600) >= 10 ? Math.floor(time / 3600) : "0" + Math.floor(time / 3600);
  time = NP.minus(time, NP.times(3600, hour));
  let min = Math.floor(time / 60) >= 10 ? Math.floor(time / 60) : "0" + Math.floor(time / 60);
  time = NP.minus(time, NP.times(60, min));
  let sec = time >= 10 ? time : "0" + time;
  return hour + ":" + min + ":" + sec;
}

export const validateEmailUtil = (email) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
}

export const errStringInit = (err) => {
  let msg = err.toString().replace(new RegExp("Error:", "ig"), "");
  return msg;
}

// 生成UUID
export const uuidv4 = () => {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
    var r = Math.random() * 16 | 0;
    var v = c === "x" ? r : (r & 3 | 8);
    return v.toString(16);
  });
}

// 防抖
export const throttle = (func, delay = 300) => {
  let timeoutId;
  return function (...args) {
    if (!timeoutId) {
      timeoutId = setTimeout(() => {
        timeoutId = null;
        func.apply(this, args);
      }, delay);
    }
  };
}

// rem初始化
export const remInit = () => {
  let domElement = window.document.documentElement;
  let clientWidth = domElement.clientWidth; //获取窗口宽度
  // console.log("domElement => ", domElement);
  // console.log("clientWidth => ", clientWidth);
  if (!clientWidth) return;
  //大于750，则给最大100px
  if (clientWidth >= 750) {
    domElement.style.fontSize = "100px";
  } else {
    //小于750，则根据750的基数*100，给字体大小
    domElement.style.fontSize = 100 * (clientWidth / 750) + "px";
  }
}